/**
 * @ClassName LC5
 * 最长回文子串
 * @Author ykx
 * @Date 2024/3/2 10:56
 * @Version 1.0
 */
public class LC5 {
    public static void main(String[] args) {
        String s = "babad";
        System.out.println("最长回文子串：" + longestPalindrome(s));
    }

    public static String longestPalindrome(String s) {
        int length = s.length();
        if (length == 0) {
            return s;
        }
        int left = 0;
        int right = 0;
        int result = 1;
        for (int i = 0; i < length; i++) {
            // 以i为中心元素，回文长度为奇数
            int l = i - 1;
            int r = i + 1;
            while (l >= 0 && r < length && s.charAt(l) == s.charAt(r)) {
                result = Math.max(result, r - l + 1);
                left = l;
                right = r;
                l--;
                r++;
            }

            // 以i与i+1为中心元素，回文长度为偶数
            l = i;
            r = i + 1;
            while (l >= 0 && r < length && s.charAt(l) == s.charAt(r)) {
                result = Math.max(result, r - l + 1);
                left = l;
                right = r;
                l--;
                r++;
            }
        }
        return s.substring(left, right + 1);
    }
}
